package org.openjsonp.json;

import javax.json.JsonString;
import javax.json.JsonValue;

/**
 * Implementation of the interface {@link javax.json.JsonString JsonString}.
 * <p>
 * This class stores the string value into a object of class {@link String}.
 * </p>
 * <p>
 * Only two constructors are providing : {@link {@link #JsonStringImpl()}
 * (default constructor) and {@link #JsonStringImpl(String)}. No others similar
 * constructors of {@link String} class are available, build a {@link String}
 * object with the appropriate constructor and use
 * {@link #JsonStringImpl(String)} instead.
 * </p>
 * <code>JsonNumber jsonNumber = new JsonNumberImpl(new String(new char[]{'J','S','O','N'}));</code>
 * 
 */
public class JsonStringImpl implements JsonString {

	private String value;

	/**
	 * Default constructor.
	 * <p>
	 * build a new JsonString with an empty string value.
	 * </p>
	 */
	public JsonStringImpl() {
		value = new String();
	}

	/**
	 * Build a new JsonString with a <b>copy</b> of the string value parameter.
	 * 
	 * @param value the string value.
	 */
	public JsonStringImpl(String value) {
		this.value = new String(value);
	}

	@Override
	public ValueType getValueType() {
		return JsonValue.ValueType.STRING;
	}

	@Override
	public String getString() {
		return value.toString();
	}

	@Override
	public CharSequence getChars() {
		return value.subSequence(0, value.length());
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (obj instanceof JsonString) {
			JsonString anotherJsonString = (JsonString) obj;
			return value.equals(anotherJsonString.getString());
		}

		if (obj instanceof String) {
			String anotherString = (String) obj;
			return value.equals(anotherString);
		}

		return false;
	}

	@Override
	public int hashCode() {
		return value.hashCode();
	}

	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("\"");
		buffer.append(value);
		buffer.append("\"");
		return buffer.toString();
	}

}
